<?php

namespace App\Supports\Payment\Methods\Balance;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Events\VipPurchasePaidEvent;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;

class PayVip extends Method implements MethodPay
{
	protected function isBalanceEnough($order)
	{
		
		return big_decimal($order->user->balances)
			->isGreaterThanOrEqualTo($order->total_amount);
	}
	
	public function validate($order = null)
	{
		/*if ($order->isPaid()) {
			fail('目标订单已支付');
		}*/
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($order->isCancelled()) {
			fail('目标订单已取消');
		}
		if (!$this->isBalanceEnough($order)) {
			fail('可用账户余额不足');
		}
	}
	
	public function info($purchase = null) {}
	
	public function pay($purchase = null)
	{
		$this->validate($purchase);
		
		return DB::transaction(function () use ($purchase) {
			
			$purchase->update(['paid_at' => Carbon::now(), 'paid_method' => 'balance']);
			
			$paidData = ['vip_purchase_id' => $purchase->id];

			account_balances($purchase->user)->minusVipPaid($purchase->total_amount, $paidData);
			
			event(new VipPurchasePaidEvent($purchase));
			
			return $purchase;
		});
	}
}
